<template>
  <el-card>
    <template #header>
      <h2>信息登记</h2>
    </template>
    <el-form :model="userInfo" label-width="auto">
      <el-form-item label="姓名：" prop="name" :rules="rules">
        <el-input v-model="userInfo.name" @blur="autofill()"/>
      </el-form-item>
      <el-form-item label="工/学号：" prop="identity" :rules="rules">
        <el-input v-model="userInfo.identity"/>
      </el-form-item>
      <el-form-item label="手机号码：" prop="phone_number" :rules="rules">
        <el-input v-model="userInfo.phone_number"></el-input>
      </el-form-item>
      <el-form-item label="借用事项：" prop="reason_type" :rules="rules">
        <el-select v-model="userInfo.reason_type" style="width: 100%">
          <el-option value="教信系教师课程及科研实践项目"></el-option>
          <el-option value="教信系学生课外学术科研项目"></el-option>
          <el-option value="教信系学生个人自立项目"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目名：" prop="reason_name" :rules="rules">
        <el-input v-model="userInfo.reason_name"></el-input>
      </el-form-item>
      <el-form-item label="取用时间：" prop="receive_time" :rules="rules">
        <el-date-picker
            v-model="userInfo.receive_time"
            type="datetime"
            placeholder="Select date and time"
            style="width: 100%"
            format="YYYY-MM-DD hh:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="归还时间：" prop="return_time" :rules="rules">
        <el-date-picker
            v-model="userInfo.return_time"
            type="datetime"
            placeholder="Select date and time"
            style="width: 100%"
            format="YYYY-MM-DD hh:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="备注：" prop="reason_name" :rules="rules">
        <el-input v-model="userInfo.note"></el-input>
      </el-form-item>
    </el-form>
  </el-card>
  <el-tabs v-model="activeName" stretch type="card">
    <el-tab-pane v-for="(obj, keyName) in devices" :key="keyName" :label="keyName">
      <DeviceForm :name="keyName" :device_json="obj"></DeviceForm>
    </el-tab-pane>
  </el-tabs>
  <el-button v-show="Object.keys(devices).length > 1" type="primary" round style="width:97%; height:45px" @click="submit">提交</el-button>
</template>

<script>
import {ElNotification} from "element-plus";

const failureNotification = (msg = '请刷新页面重新提交，或直接联系工作室成员') => {
  ElNotification({
    title: '提交失败',
    message: msg,
    type: 'error',
    duration: 0,
  })
}

import DeviceForm from "@/components/Borrow_DeviceForm";
import axios from "axios";

const categories = ['相机类', '镜头类', '电池类', '存储类', '转接类', '常用配件类', '不常用配件类'];

export default {
  name: "Borrow_Body",
  data() {
    return {
      'activeName': '0',
      'devices': {},
      'userInfo': {
        name: '',
        identity: '',
        phone_number: '',
        reason_type: '',
        reason_name: '',
        receive_time: '',
        return_time: '',
        note:'',
      },
      'rules': { required: true, message: "请填写必填项", trigger: "blur" },
    }
  },
  created() {
    window.localStorage.removeItem("Borrow")
    let checked = [];
    let device_temp = {}
      for(const v of categories) {
        axios.get("/api/getByCategory", {
          params: {
            'category': v,
          }
        }).then(res => {
          if(res.status === 200) {
            checked.push(true)
            let result = res.data;
            if(JSON.stringify(result) !== "{}"){
              device_temp[v] = result
            }
            if(checked.length === categories.length) {
              this.devices = device_temp;
            }
          }
        }).catch((e) => {
          console.log(e);
        })
      }
      this.autofill()
  },
  methods: {
    autofill() {
      if(localStorage.username !== undefined) {
        if(this.userInfo.name.length === 0)
          this.userInfo.name = localStorage.username
        if(this.userInfo.identity.length === 0)
          this.userInfo.identity = localStorage.stuID
        if(this.userInfo.phone_number.length === 0)
          this.userInfo.phone_number = localStorage.phone
      }
    },
    submit() {
      for(const key in this.userInfo) {
        if(this.userInfo[key] === '' && key !== 'note') {
          failureNotification("请填写必填项")
          return;
        }
      }
      let device_category = JSON.parse(window.localStorage["Borrow"]);
      let device = {};
      for(const category in device_category) {
        device[category] = {};
        for(const name in device_category[category]) {
          if(device_category[category][name].length > 0) {
            device[category][name] = []
            for(const num of device_category[category][name]) {
              let number = num.substr(0, 2);
              device[category][name].push(parseInt(number));
            }
          }
        }
      }
      console.log(this.userInfo.receive_time)
      let postData = {
        'name': this.userInfo.name,
        'identity': this.userInfo.identity,
        'phone_number': this.userInfo.phone_number,
        'reason_type': this.userInfo.reason_type,
        'reason_name': this.userInfo.reason_name,
        'device': device,
        'receive_time': this.userInfo.receive_time,
        'return_time': this.userInfo.return_time,
        'note': this.userInfo.note,
      };
      axios.post('/api/reserve', postData)
      .then(res => {
        if(res.status === 200) {
          this.$router.push('/result/已收到提交，我们已通知值日生为您准备')
        }else {
          failureNotification();
          console.log(postData)
        }
      }).catch(e => {
        failureNotification();
        console.log(e)
        console.log(postData)
      })
    }
  },
  components: {
    DeviceForm,
  }
}
</script>

<style scoped>

</style>